package com.portal.framework.exception.handler;

import java.text.MessageFormat;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.portal.framework.exception.AppException;
import com.portal.framework.exception.ExceptionHandleException;
import com.portal.framework.util.PropertiesSource;

/**
 * 把特定的Exception变成一个特定信息(message),这个信息从一个或多个properties文件读出
 * 
 * @author 卢烁波
 */
public class ResourceExceptionHandler extends AbstractExceptionHandler {

	private static final Log log = LogFactory
			.getLog(ResourceExceptionHandler.class);

	private PropertiesSource propertiesSource;

	public ResourceExceptionHandler(PropertiesSource ps) {
		this.propertiesSource = ps;
	}

	public ResourceExceptionHandler(Class<? extends Exception> exceptionClass,
			PropertiesSource ps) {
		this.propertiesSource = ps;
		this.exceptionClass = exceptionClass;
	}

	public ResourceExceptionHandler() {
	}

	public void handle(Throwable e) throws Throwable {
		Properties p = propertiesSource.getProperties();
		String code = e.getMessage();

		if (log.isDebugEnabled()) {
			log.debug(MessageFormat.format("进行异常处理...异常类为[{0}],异常处理类为[{1}]", e
					.getClass().getName(), this.getClass().getName()));
			log.debug("code=" + code);
		}

		String retStr = p.getProperty(code);
		if (e instanceof AppException && ((AppException) e).getArgs() != null
				&& retStr != null) {
			retStr = MessageFormat.format(retStr, ((AppException) e).getArgs());
		}

		if (log.isDebugEnabled()) {
			log.debug("properties 大小 : " + p.size());
			log.debug("retStr = " + retStr);
		}

		e.printStackTrace();

		String stackInfo = super.getStackTraceInfo(e);
		if (retStr != null) {
			throw new ExceptionHandleException(retStr, stackInfo);
		} else {
			throw new ExceptionHandleException(code, stackInfo);
		}
	}

	@Override
	public String toString() {
		return MessageFormat.format("资源信息异常类处理.处理的异常=[{0}]",
				this.exceptionClass.getName());
	}
}
